/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sip;

/**
 *
 * @author arianareyessantiago
 */
public class CheckInsulinThread implements Runnable{
    
    
    CheckStatus check;
    Alarm alarm;
    public static volatile boolean running = true;
    //first element is fatal flag and second is low flag
    boolean[] insulinFlag; 
    private int checkIntervalInSeconds;
    private int sleepIntervalInSeconds;
    private int secondsPassed;
    /**
     *
     */
    @Override
    public void run(){
        check = new CheckStatus();
        alarm = new Alarm();
        insulinFlag = new boolean[2];
        checkIntervalInSeconds = 1;
        sleepIntervalInSeconds = 300;
        secondsPassed = 300;
        
        while(running){
            //System.out.println("I am in Insulin Thread");
            insulinFlag = check.checkInsulin();
            if(insulinFlag[0] == false){
                //System.out.println("batteryFatalFlag is false");
               if(insulinFlag[1] == true){
                   //System.out.println("batteryLowFlag is true");
                   secondsPassed++;
                   if(secondsPassed >= sleepIntervalInSeconds){
                       alarm.setAlarm("Your Drug Reservoir is LOW!");
                       secondsPassed = 0;
                   }
                   try{
                       Thread.sleep(sleepIntervalInSeconds*1000);
                    }catch(InterruptedException e){ 
                        SipLogger.Instance().debug("CheckBatteryThread has been Interrupted");
                    } 
               }
            }
            else if(insulinFlag[0] == true){
                try{
                    Thread.sleep(10*1000);
                }catch(InterruptedException e){ 
                    SipLogger.Instance().debug("CheckBatteryThread has been Interrupted");
                }
                
                System.exit(1);
            }
            //SipLogger.Instance().info("Insulin Reservoir was checked.");
            
            try{
                Thread.sleep(checkIntervalInSeconds*1000);
            }
            catch(InterruptedException e){   
            }

        }  
    }
    public void terminate(){
        SipLogger.Instance().debug("CheckInsulinThread has been Terminated");
        running = false;
    }
    
}
